<template>
  <view class="notifications">
    <!-- 消息类型筛选 -->
    <view class="type-filter">
      <view 
        v-for="(type, index) in messageTypes" 
        :key="index"
        :class="['filter-item', { active: currentType === type.id }]"
        @click="selectType(type.id)"
      >
        {{type.name}}
        <text class="badge" v-if="type.count">{{type.count}}</text>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view class="message-list" scroll-y v-if="filteredMessages.length">
      <view 
        v-for="(message, index) in filteredMessages" 
        :key="index"
        :class="['message-item', { unread: !message.read }]"
        @click="viewMessage(message)"
      >
        <view class="message-icon">
          <uni-icons :type="message.icon" size="24" :color="message.iconColor" />
        </view>
        <view class="message-content">
          <view class="message-header">
            <text class="title">{{message.title}}</text>
            <text class="time">{{formatTime(message.time)}}</text>
          </view>
          <text class="preview">{{message.content}}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <image src="/static/empty-message.png" mode="aspectFit" />
      <text>暂无消息通知</text>
    </view>

    <!-- 全部已读按钮 -->
    <view class="mark-read-btn" v-if="hasUnread" @click="markAllRead">
      全部已读
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      messageTypes: [
        { id: 'all', name: '全部', count: 0 },
        { id: 'system', name: '系统', count: 0 },
        { id: 'activity', name: '活动', count: 0 },
        { id: 'care', name: '养护', count: 0 }
      ],
      currentType: 'all',
      messages: [],
      messageIcons: {
        system: 'info',
        activity: 'notification',
        care: 'heart'
      }
    }
  },
  computed: {
    filteredMessages() {
      if (this.currentType === 'all') {
        return this.messages
      }
      return this.messages.filter(msg => msg.type === this.currentType)
    },
    hasUnread() {
      return this.messages.some(msg => !msg.read)
    }
  },
  methods: {
    selectType(typeId) {
      this.currentType = typeId
    },
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date

      // 24小时内显示相对时间
      if (diff < 24 * 60 * 60 * 1000) {
        if (diff < 60 * 60 * 1000) {
          return Math.floor(diff / (60 * 1000)) + '分钟前'
        }
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
      }

      // 超过24小时显示具体日期
      return date.getFullYear() + '-' + 
             String(date.getMonth() + 1).padStart(2, '0') + '-' + 
             String(date.getDate()).padStart(2, '0')
    },
    async loadMessages() {
      try {
        const res = await uniCloud.callFunction({
          name: 'getMessages',
          data: {}
        })
        if (res.result.code === 200) {
          this.messages = res.result.data
          this.updateTypeCounts()
        }
      } catch (error) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },
    updateTypeCounts() {
      const counts = {
        system: 0,
        activity: 0,
        care: 0
      }
      this.messages.forEach(msg => {
        if (!msg.read && counts[msg.type] !== undefined) {
          counts[msg.type]++
        }
      })
      this.messageTypes = this.messageTypes.map(type => ({
        ...type,
        count: type.id === 'all' ? 
          Object.values(counts).reduce((a, b) => a + b, 0) : 
          counts[type.id] || 0
      }))
    },
    async viewMessage(message) {
      if (!message.read) {
        try {
          await uniCloud.callFunction({
            name: 'markMessageRead',
            data: { messageId: message._id }
          })
          message.read = true
          this.updateTypeCounts()
        } catch (error) {
          console.error('标记已读失败:', error)
        }
      }
      // TODO: 查看消息详情
      uni.showToast({
        title: '查看消息详情',
        icon: 'none'
      })
    },
    async markAllRead() {
      try {
        await uniCloud.callFunction({
          name: 'markAllMessagesRead',
          data: {}
        })
        this.messages.forEach(msg => msg.read = true)
        this.updateTypeCounts()
        uni.showToast({
          title: '已全部标记为已读',
          icon: 'success'
        })
      } catch (error) {
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    }
  },
  onShow() {
    this.loadMessages()
  }
}
</script>

<style lang="scss">
.notifications {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: env(safe-area-inset-bottom);
}

.type-filter {
  display: flex;
  background: #fff;
  padding: 20rpx;
  border-bottom: 1px solid #f5f5f5;

  .filter-item {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    position: relative;
    padding: 12rpx 0;

    &.active {
      color: #5cb85c;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background: #5cb85c;
        border-radius: 2rpx;
      }
    }

    .badge {
      position: absolute;
      top: 0;
      right: 50%;
      transform: translateX(20rpx);
      background: #ff4d4f;
      color: #fff;
      font-size: 20rpx;
      padding: 2rpx 8rpx;
      border-radius: 20rpx;
      min-width: 28rpx;
      text-align: center;
    }
  }
}

.message-list {
  height: calc(100vh - 180rpx);

  .message-item {
    display: flex;
    padding: 30rpx 20rpx;
    background: #fff;
    border-bottom: 1px solid #f5f5f5;
    position: relative;

    &.unread {
      background: #f8f8f8;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        width: 6rpx;
        height: 100%;
        background: #5cb85c;
      }
    }

    .message-icon {
      width: 80rpx;
      height: 80rpx;
      background: #f5f5f5;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
    }

    .message-content {
      flex: 1;

      .message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8rpx;

        .title {
          font-size: 30rpx;
          color: #333;
          font-weight: bold;
        }

        .time {
          font-size: 24rpx;
          color: #999;
        }
      }

      .preview {
        font-size: 26rpx;
        color: #666;
        line-height: 1.5;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }

  text {
    color: #999;
    font-size: 28rpx;
  }
}

.mark-read-btn {
  position: fixed;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
  background: #5cb85c;
  color: #fff;
  padding: 20rpx 60rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  box-shadow: 0 4rpx 12rpx rgba(92, 184, 92, 0.3);
}
</style> 